/**
 * MasicTiming
 * <p/>
 * User: joakimd
 * Date: 2013-03-19
 * Time: 13:41
 */
package org.dru.masic {
public class MasicTiming {
    private var _beatsPerMinute: int;
    private var _ticksPerBeat: int;
    private var _valid: Boolean;
    private var _samplesPerTick: Number;

    public function MasicTiming(beatsPerMinute: int = 120, ticksPerBeat: int = 96) {
        this.beatsPerMinute = beatsPerMinute;
        this.ticksPerBeat = ticksPerBeat;
    }


    public function get beatsPerMinute(): int {
        return _beatsPerMinute;
    }

    public function set beatsPerMinute(value: int): void {
        if (value != _beatsPerMinute) {
            _beatsPerMinute = value;
            invalidate();
        }
    }

    public function get ticksPerBeat(): int {
        return _ticksPerBeat;
    }

    public function set ticksPerBeat(value: int): void {
        if (value != _ticksPerBeat) {
            _ticksPerBeat = value;
            invalidate();
        }
    }

    private function invalidate(): void {
        _valid = false;
    }

    private function validate(): void {
        if (!_valid) {
            _samplesPerTick = Number(60 * MasicConstants.SAMPLE_RATE / _beatsPerMinute) / Number(_ticksPerBeat);
            _valid = true;
        }
    }

    public function get samplesPerTick(): Number {
        validate();
        return _samplesPerTick;
    }

    public function toSample(tick: int): int {
        return int(samplesPerTick * Number(tick));
    }
}
}
